package com.sinopec.handdevice.view

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import com.jakewharton.rxbinding3.view.clicks
import com.sinopec.basemodule.base.BaseActivity
import com.sinopec.basemodule.base.CustomToolbar
import com.sinopec.basemodule.utils.ToastUtils
import com.sinopec.handdevice.R
import com.sinopec.handdevice.constants.CustomAppUpdateContract
import com.sinopec.handdevice.presenter.CustomAppUpdatePresenter
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.view_app_update_tip_layout.*
import java.util.concurrent.TimeUnit

/**
 * @Description: 本地更新界面
 * @ClassName: CustomAppUpdateActivity
 * @author lwj
 * @date 2022/8/25 15:42
 */
class CustomAppUpdateActivity : BaseActivity<CustomAppUpdatePresenter>(),
    CustomAppUpdateContract.View {

    companion object {
        private const val INTENT_IS_FORCE_TAG: String = "intent_is_force_tag"
        private const val INTENT_UPDATE_DESC_TAG: String = "intent_update_desc_tag"
        private const val INTENT_APP_UPDATE_URL_TAG: String = "intent_app_update_url_tag"

        private const val DOWNLOAD_SUCCESS_FLAG: Int = 100

        fun start(
            context: Context?,
            isForce: Boolean? = false,
            updateDesc: String?,
            appUpdateUrl: String?
        ) {
            val intent = Intent(context, CustomAppUpdateActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.putExtra(INTENT_IS_FORCE_TAG, isForce)
            intent.putExtra(INTENT_UPDATE_DESC_TAG, updateDesc)
            intent.putExtra(INTENT_APP_UPDATE_URL_TAG, appUpdateUrl)
            context?.startActivity(intent)
        }
    }

    private var downLoadProgress: Int? = null

    private val isForce: Boolean by lazy {
        intent.getBooleanExtra(INTENT_IS_FORCE_TAG, false)
    }

    private val updateDesc: String? by lazy {
        intent.getStringExtra(INTENT_UPDATE_DESC_TAG)
    }

    private val appUpdateUrl: String? by lazy {
        intent.getStringExtra(INTENT_APP_UPDATE_URL_TAG)
    }

    override fun refreshDownLoadProgress(value: Int) {
        downLoadProgress = value
        app_update_confirm.text = if (value < DOWNLOAD_SUCCESS_FLAG) {
            "正在下载:${value}%"
        } else {
            app_update_confirm.isEnabled = true
            "立即安装"
        }
    }

    override fun downloadErrorRefreshUi() {
        app_update_confirm.text = resources.getString(R.string.app_update_confirm)
        app_update_confirm.isEnabled = true
        downLoadProgress = 0
    }

    override fun getContentView(): Int {
        return R.layout.view_app_update_tip_layout
    }

    override fun configToolbar(rToolbar: CustomToolbar?) {
        rToolbar?.setToolbarVisible(false)
        rToolbar?.hideStatusLine(true)
    }

    override fun initView(savedInstanceState: Bundle?) {
        smoothScreen()
        mPresenter = CustomAppUpdatePresenter(this)
        viewContainer?.setBackgroundResource(Color.TRANSPARENT)

        app_update_cancel.visibility = if (isForce) View.INVISIBLE else View.VISIBLE

        app_update_top_background_desc_rv_show.text = updateDesc
    }

    override fun initEvent() {
        super.initEvent()
        app_update_confirm.click {
            if (downLoadProgress == DOWNLOAD_SUCCESS_FLAG) {
                mPresenter.onInstall()
            } else {
                val rxPermissions = RxPermissions(this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe {
                        if (it) {
                            if (TextUtils.isEmpty(appUpdateUrl)) {
                                ToastUtils.showToast("无效的下载地址")
                                return@subscribe
                            }

                            app_update_confirm.text = "准备下载中，请稍候..."
                            app_update_confirm.isEnabled = false
                            mPresenter.initDownloadListener(appUpdateUrl)
                        } else {
                            mPresenter.onStoragePermissionNotGranted()
                        }
                    }
                addDisposable(rxPermissions)
            }
        }

        app_update_cancel.click {
            mPresenter.cancelDownloadListener()
            finish()
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
    }

    private fun View.click(call: Consumer<Unit>) {
        addDisposable(
            this.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(call)
        )
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return if (isForce) true else super.onKeyDown(keyCode, event)
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 处理activity 以 dialog 样式弹出时会发生抖动的问题
     */
    private fun smoothScreen() {
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                val rootView: ViewGroup = findViewById<View>(android.R.id.content) as ViewGroup
                val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
                val statusBarHeight = resources.getDimensionPixelSize(resourceId)
                rootView.setPadding(0, statusBarHeight, 0, 0)
                window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.cancelDownloadListener()
    }
}